package com.coding.task;

import com.alibaba.fastjson2.JSON;
import com.coding.entity.LiveMessage;
import com.coding.handler.LiveWebSocketHandler;
import com.coding.utils.Constant;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/7/19 10:13:32
 */
@Slf4j
@EnableScheduling
@EnableAsync
@Component
public class LiveTask {
    @Resource
    private RedisTemplate<String, Integer> MyRedisTemplate;

//    @Resource
//    private RedissonClient redissonClient;


    @Async("taskExecutor")
    @Scheduled(cron = "0/5 * * * * ?")
    public void processBatchLikes() {
        log.info("点赞任务的线程号ID==>{}", Thread.currentThread().getId());
        sendLikesToFront();


    }

    @Async("taskExecutor")
    @Scheduled(cron = "0/3 * * * * ?")
    public void processBatchOnline() {
        log.info("在线任务的线程号ID==>{}", Thread.currentThread().getId());
        sendOnlineNumToFront();

    }

    /**
     * 发送在线人数到前端
     */
    private void sendOnlineNumToFront() {
        log.info("发送在线人数到前端 开始-----------------");

        int count = 0;
        Set<String> keys = MyRedisTemplate.keys(Constant.REDIS_ROOM_KEY_PREFIX + "*");
        if (keys == null || keys.isEmpty()) {
            log.info("没有直播间 结束-----------------");
            return;
        }
        long start = System.currentTimeMillis();
        for (String o : keys) {
            String liveStreamId = o.substring(Constant.REDIS_ROOM_KEY_PREFIX.length());
            // 获取在线人数

            int onlineNum = LiveWebSocketHandler.getSessions().values().stream()
                    .filter(session -> liveStreamId.equals(session.getAttributes().get("roomId")))
                    .mapToInt(session -> 1).sum();

            LiveMessage likeVo = new LiveMessage();
            likeVo.setOnlineNum(onlineNum);
            likeVo.setType(2);
            likeVo.setRoomId(liveStreamId);
            log.info("直播间：{}，在线人数: {}", liveStreamId, onlineNum);
            LiveWebSocketHandler.broadcast(liveStreamId, JSON.toJSONString(likeVo));
        }
        long end = System.currentTimeMillis();
        log.info("发送在线人数到前端 耗时: {}ms", end - start);
    }

    /**
     * 发送点赞数到前端
     */
    private void sendLikesToFront() {
        log.info("发送点赞数到前端 开始-----------------");
        // 获取所有点赞数的key
        Set<String> keys = MyRedisTemplate.keys(Constant.REDIS_LIKE_KEY_PREFIX + "*");
        if (keys == null || keys.isEmpty()) {
            log.info("没有点赞数据 结束-----------------");
            return;
        }
        long start = System.currentTimeMillis();
        for (String key : keys) {
            // 获取点赞数
            String likeCount = String.valueOf(MyRedisTemplate.opsForValue().get(key));
            // 获取直播间id
            String liveStreamId = key.substring(Constant.REDIS_LIKE_KEY_PREFIX.length());
            LiveMessage liveMessage = new LiveMessage();
            liveMessage.setContent(likeCount);
            liveMessage.setRoomId(liveStreamId);
            liveMessage.setType(0);
            // 发送点赞数到前端
            LiveWebSocketHandler.broadcast(liveStreamId, JSON.toJSONString(liveMessage));
        }
        long end = System.currentTimeMillis();
        log.info("发送点赞数到前端 耗时: {}ms", end - start);
    }
}
